<template>
  <div class="news-manage">
    <div class="page-header">
      <h2>用户反馈</h2>
    </div>
    
    <!-- 查询表单 -->
    <div class="search-bar">
      <el-form :model="queryForm" inline>
        <el-form-item label="反馈类型">
          <el-select
            v-model="queryForm.type"
            placeholder="请选择反馈类型"
            size="large"
            style="width: 240px;"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="处理状态">
          <el-select
            v-model="queryForm.status"
            placeholder="请选择处理状态"
            size="large"
            style="width: 240px;"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!--  -->
      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stats-row">
        <el-col 
          v-for="(value, key) in feedbackStats" 
          :key="key" 
          :span="6"
        >
          <el-statistic :title="getTitle(key)" :value="value">
            <template #prefix v-if="key === 'Bug反馈'">
              <el-icon style="vertical-align: -0.125em">
                <Warning />
              </el-icon>
            </template>
            <template #prefix v-else-if="key === '功能建议'">
              <el-icon style="vertical-align: -0.125em">
                <LightBulb />
              </el-icon>
            </template>
            <template #prefix v-else-if="key === '投诉'">
              <el-icon style="vertical-align: -0.125em">
                <Bell />
              </el-icon>
            </template>
            <template #prefix v-else>
              <el-icon style="vertical-align: -0.125em">
                <QuestionFilled />
              </el-icon>
            </template>
          </el-statistic>
        </el-col>
      </el-row>
    </div>
    
    <!-- 反馈列表 -->
    <div class="news-table">
      <table>
        <thead>
          <tr>
            <th>反馈ID</th>
            <th>反馈类型</th>
            <th>反馈内容</th>
            <th>处理状态</th>
            <th>处理管理员Id</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="feedback in paginatedNewsList" :key="feedback.feedback_id">
            <td>{{ feedback.feedback_id }}</td>
            <td>{{ getTypeLabel(feedback.type) }}</td>
            <td>{{ feedback.content }}</td>
            <td>
              <el-button plain :type="getStatusButtonType(feedback.status)" size="small">
                {{ getStatusLabel(feedback.status) }}
              </el-button>
            </td>
            <td>{{ feedback.admin_id }}</td>
            <td>{{ formatDate(feedback.create_time) }}</td>
            <td>
              <button class="edit-btn" @click="handleView(feedback.feedback_id)">查看</button>
              <button class="edit-btn" @click="handleEdit(feedback)">处理/编辑</button>
              <button class="delete-btn" @click="handleDelete(feedback.feedback_id)">
                删除
              </button>
            </td>
          </tr>
        </tbody>
      </table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </div>

    <!-- 查看详情对话框 -->
    <div class="dialog" v-if="showViewDialog" @click.self="closeViewDialog">
        <div class="dialog-content">
        <h3>反馈详情</h3>
        <div class="detail-group">
            <label>反馈ID：</label>
            <span>{{ viewFeedback.feedback_id }}</span>
        </div>
        <div class="detail-group">
            <label>用户id：</label>
            <span>{{ viewFeedback.user_id }}</span>
        </div>
        <div class="detail-group">
            <label>用户名：</label>
            <span>{{ viewFeedback.userName }}</span>
        </div>
        <div class="detail-group">
            <label>反馈类型：</label>
            <span>{{ getTypeLabel(viewFeedback.type) }}</span>
        </div>
        <div class="detail-group">
            <label>处理状态：</label>
            <span>{{ getStatusLabel(viewFeedback.status) }}</span>
        </div>
        <div class="detail-group">
            <label>反馈内容：</label>
            <div class="content-box">{{ viewFeedback.content }}</div>
        </div>
        <div class="detail-group">
            <label>联系方式：</label>
            <span>{{ viewFeedback.contact }}</span>
        </div>
        <div class="detail-group">
            <label>处理管理员：</label>
            <span>{{ viewFeedback.admin_id || '未处理' }}</span>
        </div>
        <div class="detail-group">
            <label>回复内容</label>
            <div class="content-box">{{ viewFeedback.response }}</div>
        </div>
        <div class="detail-group">
            <label>创建时间：</label>
            <span>{{ formatLongDate(viewFeedback.create_time) }}</span>
        </div>
        <div class="detail-group">
            <label>回复时间</label>
            <span>{{ formatLongDate(viewFeedback.response_time) }}</span>
        </div>

        <div class="dialog-footer">
            <button class="cancel-btn" @click="closeViewDialog">关闭</button>
        </div>
        </div>
    </div>

    <!-- 编辑对话框 - 改为el-dialog形式 -->
  <el-dialog
    v-model="showDialog"
    title="处理反馈"
    width="50%"
    :before-close="closeDialog"
    >
        <el-form :model="currentFeedback" label-width="100px">
        <!-- 反馈ID（不可编辑） -->
        <el-form-item label="反馈ID：">
            <el-input v-model="currentFeedback.feedback_id" disabled />
        </el-form-item>
        
        <!-- 反馈内容（不可编辑） -->
        <el-form-item label="反馈内容：">
            <el-input
            v-model="currentFeedback.content"
            type="textarea"
            :rows="4"
            disabled
            />
        </el-form-item>

        <!-- 新增：处理管理员ID（可编辑） -->
      <el-form-item label="处理管理员ID：">
        <el-input
          v-model="currentFeedback.admin_id"
          placeholder="请输入处理管理员ID"
        />
      </el-form-item>
        
        <!-- 处理状态（可编辑） -->
        <el-form-item label="处理状态：">
            <el-select
            v-model="currentFeedback.status"
            placeholder="请选择处理状态"
            style="width: 100%"
            >
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
            </el-select>
        </el-form-item>

        
        <!-- 回复内容（可编辑） -->
        <el-form-item label="回复内容：">
            <el-input
            v-model="currentFeedback.response"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
            />
        </el-form-item>
        </el-form>
        
        <template #footer>
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
        </template>
  </el-dialog>
  </div>
  </template>

<script setup>
import { ref, onMounted, computed } from "vue";
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus"; 

// 查询表单
const queryForm = ref({
  pageNo: 1,
  type: '',
  status: ''
});

// 下拉选项
const typeOptions = [
  { value: 'bug', label: 'Bug反馈' },
  { value: 'suggestion', label: '功能建议' },
  { value: 'complaint', label: '投诉' },
  { value: 'question', label: '其他问题' }
];

const statusOptions = [
  { value: 'pending', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'resolved', label: '已解决' },
  { value: 'closed', label: '拒绝' }
];

const feedbackList = ref([]);
const showDialog = ref(false);
const currentFeedback = ref({
  feedback_id: null,
  content: '',
  status: '',
   admin_id: null,
  response: '',
  response_time: ''
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = computed(() => feedbackList.value.length);

// 计算分页后的数据
const paginatedNewsList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return feedbackList.value.slice(start, end);
});

// 处理页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
};

// 处理每页条数改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 查询方法
const handleQuery = () => {
  currentPage.value = 1;
  fetchFeedbackList();
};

// 重置查询
const resetQuery = () => {
  queryForm.value = {
    pageNo: 1,
    type: '',
    status: ''
  };
  handleQuery();
};

// 获取反馈列表
const fetchFeedbackList = async () => {
  try {
    const params = {
      pageNo: queryForm.value.pageNo,
      type: queryForm.value.type,
      status: queryForm.value.status
    };
    
    const response = await axios.get("/api/feekback/queryFeekback", { params });
    if (response.data.code === 200) {
      feedbackList.value = response.data.data.list || [];
    } else {
      ElMessage.error(response.data.message || '获取数据失败');
    }
  } catch (error) {
    console.error("获取反馈列表失败:", error);
    ElMessage.error('获取反馈列表失败');
  }
};

const getStatusButtonType = (status) => {
  switch(status) {
    case 'resolved': return 'success';  // 绿色
    case 'processing': return 'primary'; // 蓝色
    case 'closed': return 'info';     // 灰色
    case 'pending':return  'warning'  // 默认无色
  }
};


// 格式化短日期
const formatDate = (dateString) => {
  if (!dateString) return '-';
  
  const date = new Date(dateString);
  
  // 获取各个时间部分
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day} `;
};


// 长日期格式 YYYY-MM-dd HH:mm:ss
const formatLongDate = (dateString) => {
    if (!dateString) return '-';
  
  const date = new Date(dateString);
  
  // 获取各个时间部分
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 显示编辑对话框
const handleEdit = (feedback) => {
   currentFeedback.value = { 
    ...feedback,
    // 初始化回复时间为当前时间
    response_time: new Date().toISOString()
  }
  showDialog.value = true
};

// 关闭对话框
const closeDialog = () => {
  showDialog.value = false;
  currentFeedback.value = {
    feedback_id: null,
    type: '',
    status: '',
    content: ''
  };
};

// 保存反馈
const handleSave = async () => {
  try {
    // 更新回复时间为当前时间
    currentFeedback.value.response_time = new Date().toISOString()
    
    const response = await axios.post(
      "/api/feekback/updateFeekback",
      currentFeedback.value
    )
    
    if (response.data.code === 200) {
      ElMessage.success(response.data.data || '更新成功')
      closeDialog()
      fetchFeedbackList()
    } else {
      ElMessage.error(response.data.message || '更新失败')
    }
  } catch (error) {
    ElMessage.error('操作失败')
    console.error("保存反馈失败:", error)
  }
};

// 删除反馈
const handleDelete = async (feedback_id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条用户反馈吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await axios.delete(`/api/feekback/delFeekback/${feedback_id}`);
    if (response.data.code === 200) {
      ElMessage.success('删除成功');
      fetchFeedbackList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
      console.error("删除反馈失败:", error);
    }
  }
};

//-------------- 查看相关状态-------------
const showViewDialog = ref(false)
const viewFeedback = ref({
  feedback_id: null,
  userName:'',
  user_id:'',
  type: '',
  status: '',
  content: '',
  admin_id: null,
  create_time: '',
  contact:'',
  response:'',
  response_time:'',
})

// 获取类型标签
const getTypeLabel = (value) => {
  const item = typeOptions.find(opt => opt.value === value)
  return item ? item.label : value
}

// 获取状态标签
const getStatusLabel = (value) => {
  const item = statusOptions.find(opt => opt.value === value)
  return item ? item.label : value
}

// 查看详情
const handleView = async (feedback_id) => {
  try {
    const response = await axios.get("/api/feekback/queryFeekbackById", {
      params: { feedback_id }
    })
    if (response.data.code === 200) {
      viewFeedback.value = response.data.data
      showViewDialog.value = true
    } else {
      ElMessage.error(response.data.message || '获取详情失败')
    }
  } catch (error) {
    console.error("获取反馈详情失败:", error)
    ElMessage.error('获取反馈详情失败')
  }
}

// 关闭查看对话框
const closeViewDialog = () => {
  showViewDialog.value = false
  viewFeedback.value = {
    feedback_id: null,
    type: '',
    status: '',
    content: '',
    admin_id: null,
    create_time: ''
  }
}

// 反馈统计数据
const feedbackStats = ref({
  '其他问题': 0,
  '投诉': 0,
  '功能建议': 0,
  'Bug反馈': 0
})

// 获取反馈统计数据
const fetchFeedbackStats = async () => {
  try {
    const response = await axios.get("api/feekback/status")
    if (response.data.code === 200 && response.data.data) {
      feedbackStats.value = {
        '其他问题': response.data.data.question || 0,
        '投诉': response.data.data.complaint || 0,
        '功能建议': response.data.data.suggestion || 0,
        'Bug反馈': response.data.data.bug || 0
      }
    }
  } catch (error) {
    console.error('获取反馈统计数据失败:', error)
  }
}

// 获取统计项的标题
const getTitle = (key) => {
  return key; // 直接返回key，因为我们已经映射为中文
}

onMounted(() => {
  fetchFeedbackList();
  fetchFeedbackStats();
  
});
</script>

<style scoped>
.news-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.news-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  padding: 12px 16px;
  text-align: left;
  border-bottom: 1px solid #e8e8e8;
}

th {
  background-color: #fafafa;
  font-weight: 500;
}

.edit-btn,
.delete-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  margin-right: 8px;
  cursor: pointer;
}

.edit-btn {
  background-color: #1890ff;
  color: white;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-content {
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 600px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.form-group textarea {
  width: 100%;
  height: 120px;
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  resize: vertical;
}

.dialog-footer {
  margin-top: 24px;
  text-align: right;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  margin-left: 8px;
  cursor: pointer;
}

.cancel-btn {
  background-color: #f4f4f5;
  color: #606266;
}

.confirm-btn {
  background-color: #1890ff;
  color: white;
}

.pagination-container {
  padding: 20px;
  display: flex;
  justify-content: center;
}

.search-bar {
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-right: 16px;
  margin-bottom: 0;
}

.detail-group {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
}

.detail-group label {
  width: 100px;
  font-weight: bold;
  color: #606266;
}

.detail-group span {
  flex: 1;
}

.content-box {
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fafafa;
  white-space: pre-wrap;
  word-break: break-word;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-textarea) textarea {
  min-height: 100px;
}

/* 添加统计卡片样式 */
.el-statistic {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.el-statistic__head {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.el-statistic__content {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

/* 调整统计卡片间距 */
.search-bar .el-row {
  margin-top: 20px;
  margin-bottom: 20px;
}

.search-bar .el-col {
  padding-left: 10px !important;
  padding-right: 10px !important;
}
</style>